package com.bckj.fastboot.paid.biz.interfaces.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.bckj.fastboot.core.util.WebUtils;
import com.bckj.fastboot.paid.api.model.PayConfigQuery;
import com.bckj.fastboot.paid.biz.application.service.PayResultService;
import com.bckj.fastboot.paid.biz.infrastructure.mapper.PayConfigMapper;
import com.bckj.fastboot.paid.biz.infrastructure.sdk.wechatpay.model.WechatPayResultRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
@RequestMapping("pay/result")
public class PayResultController {

    private final PayResultService payResultService;
    private final PayConfigMapper payConfigMapper;

    /**
     * 微信支付回调
     */
    @RequestMapping("wxpay/{outMerchantId}")
    public Object wxpay(@PathVariable("outMerchantId") String outMerchantId) {
        return payResultService.wechatPayResult(buildWechatPayResultRequest(outMerchantId));
    }

    private WechatPayResultRequest buildWechatPayResultRequest(String outMerchantId) {
        HttpServletRequest request = WebUtils.getRequest();
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String body = stringBuilder.toString();
        return  WechatPayResultRequest.create()
                .setOutMerchantId(outMerchantId)
                .setSignature(request.getHeader("Wechatpay-Signature"))
                .setNonce(request.getHeader("Wechatpay-Nonce"))
                .setSerialNumber(request.getHeader("Wechatpay-Serial"))
                .setTimestamp(request.getHeader("Wechatpay-Timestamp"))
                .setBody(body);
    }

    /**
     * 微信支付回调
     */
    @SaIgnore
    @RequestMapping("alipay")
    public Object alipay(@RequestBody PayConfigQuery query) {
        return payConfigMapper.queryByCondition(query);
    }
}
